import { useRef , useState} from "react";
import UseRefChild from "./useRefChild";

const UseRefCurrent = () => {
   // ref 累加
   const num1 = useRef(0)
  const updateNum = () => {
     console.log('num1-prev', num1.current) // obj.current
     num1.current++
     console.log('num1-current', num1.current) 
   }

//  useRef 获取dom元素的value
  const inputref = useRef(null)
  const refEle = useRef(null)
    const getRef = () => {
     console.log('inputref内容', inputref.current.value)
     inputref.current.focus()
     let pel = document.getElementById('pel')
     console.log('refEle-innerHtml', refEle.current.innerHTML,pel.innerHTML)
   }
   
   // useRef 挂载到子组件上
    // 1. 父组件传值给子组件 forwardRef
   const child1 = useRef(100)
   const getRefChild = () => {
     console.log('child ref', child1)
   
   }
   // 2. 父组件想调用子组件属性的方法/或者访问子组件的属性或方法需要用 useImperativeHandle暴露
   
   // 子组件要操作父组件的数据
//    const [list, setList] = useState([1,2,3])
   const [list, setList] = useState({
     list: [{
        name: 'aa',
        age: 10
      }],
      level: 1
   }
   
   )
   const updateList = (item) => {
    //    list.push(item)
    let nList = list.list
    nList.push(item)
    // const nList = [...list].concat([...item])
    setList(() => {
       return {
         ...list,
         list:nList
       }
    })
    console.log('==', list)
   }
   
   
    return (<div>
      <h2>useRef</h2>
      <h3>1.ref挂载到react元素上</h3>
      num1: {num1.current}<br/>
      <button onClick={updateNum}>ref-num1++</button><br/>
      
      <input type="text" ref={inputref} />
      <button onClick={getRef}>获取input内容</button>
      <p id="pel" ref={refEle}>这是一段段落</p>
      <button onClick={getRef}>获取标签（元素）内容innerHTML</button>
      
      {/* ref-挂载-父组件访问子组件的数据（属性/方法） */}
      <h3>2.ref-挂载子组件上-父组件访问子组件的数据（属性/方法）</h3>
      <UseRefChild ref={child1} list={list} updateList={updateList} />
      <button onClick={getRefChild}>获取子组件的内容</button>
    </div>);
}
 
export default UseRefCurrent;